package com.bieyang.anjia.ui.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bieyang.anjia.R;
import com.bieyang.anjia.net.NetManager;

import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SharedPrefsUtil;
import com.bieyang.anjia.utils.Show;
import com.bieyang.anjia.utils.SubUtils;

public class AcRegister extends BaseActivity implements OnFocusChangeListener,
		OnClickListener {

	public EditText userName, password, phone, email, alias, etCode,
			passwordAgain;
	TextView tvXieyi;
	public String name, pass, code, ema, ali, uuid, passAgain;

	public Button back, sure, btnYanzheng;
	public ProgressDialog pd;
	public String erro = null;
	public boolean runTime;
	int timeNum = 60;
	Context con;
	@SuppressLint("HandlerLeak")
	private Handler Uihandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Constants.REGISTER_SUCESS:
				Show.toast(con, R.string.tip_register_ok);
				saveLoginInfo(name, pass);
				Intent it = new Intent(con, AcChooseZhuji.class); // 开启服务
				startActivity(it);
				finish();
				break;
			case Constants.REGISTER_FAIL:
				Show.toast(con, R.string.tip_register_fail);
				break;
			case Constants.REGISTER_EXIT_USER:
				Show.toast(con, R.string.tip_register_eixt);
				userName.setText(R.string.tip_register_eixt);
				break;
			case Constants.CODE_ERROR:
				btnYanzheng.setEnabled(true);
				Show.toast(con, R.string.tip_code_error);
				break;
			case Constants.CODE_SUCCESS:
				btnYanzheng.setEnabled(false);
				codeSuccess();
				break;
			case Constants.CODE_FAIL:
				btnYanzheng.setEnabled(true);
				Show.toast(con, R.string.register_code_fail);
				break;
			case 6060:
				if (timeNum > 0) {
					btnYanzheng.setText(String.valueOf(timeNum) + "s后再获取");
				} else {					
					btnYanzheng.setEnabled(true);				 
					btnYanzheng.setText("获取验证码"); 
				}

				break;

			default:
				break;
			}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.acregister);
		con = AcRegister.this;
		App.mContext = AcRegister.this;

		userName = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		passwordAgain = (EditText) findViewById(R.id.passwordAgain);
		etCode = (EditText) findViewById(R.id.etCode);

		tvXieyi = (TextView) findViewById(R.id.tvXieyi);
		tvXieyi.setOnClickListener(this);
		back = (Button) findViewById(R.id.btnBack);
		sure = (Button) findViewById(R.id.btnSave);
		btnYanzheng = (Button) findViewById(R.id.btnYanzheng);
		btnYanzheng.setOnClickListener(this);

		alias = (EditText) findViewById(R.id.alias);
		phone = (EditText) findViewById(R.id.phone);
		// email = (EditText) findViewById(R.id.email);
		userName.setOnFocusChangeListener(this);
		password.setOnFocusChangeListener(this);
		alias.setOnFocusChangeListener(this);
		phone.setOnFocusChangeListener(this);
		// email.setOnFocusChangeListener(this);
		// confirm.setOnFocusChangeListener(this);
		back.setOnClickListener(this);
		sure.setOnClickListener(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	void saveLoginInfo(String userName, String passWord) {
		SharedPrefsUtil.putValue(con, "phone", userName);
		SharedPrefsUtil.putValue(con, "password", passWord);

	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			goBack();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnBack:
			goBack();
			break;
		case R.id.tvXieyi: // 安加协议
			startActivity(new Intent(con, AcAnjiaXieyi.class));
			break;
		case R.id.btnYanzheng:
			 
			timeNum=60;
			name = userName.getText().toString().trim();
			if (!checkPhone(name)) {
				return;
			}
			btnYanzheng.setEnabled(false);
			getRegisterCode(name);
			break;

		case R.id.btnSave:
			name = userName.getText().toString().trim();
			pass = password.getText().toString().trim();
			code = etCode.getText().toString().trim();
			passAgain = passwordAgain.getText().toString().trim();
			uuid = SubUtils.getUuid(con);
			if (checkUser(name, pass, passAgain))
				register(name, pass, uuid, code);

			break;
		default:
			break;
		}

	}

	void getRegisterCode(String name) {

	App.netManager.getRegisterCode(name, Uihandler);

	}

	private void codeSuccess() {

		Show.toast(con, R.string.register_code_ok);

		btnYanzheng.setEnabled(false);
		runTime = true;
		new Thread() {
			public void run() {
				while (timeNum>=0) {
					try {		
						Thread.sleep(1000);
						Uihandler.sendEmptyMessage(6060);
						timeNum--;
						
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
		}.start();

	}

	void goBack() {
		Intent intent = new Intent(AcRegister.this, AcTiYan.class);
		startActivity(intent);
		finish();
	}

	void register(final String name, final String pass, String uuid, String code) {
		App.netManager.register(name, pass, uuid, code, Uihandler);

	}

	public class RegisterThread extends AsyncTask<Void, Void, Integer> {

		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			pd.dismiss();
			// if (result > 0) {
			// Show.toast(AcRegister.this, R.string.register_success);
			// finish();
			// } else {
			// if (erro.contains("�û���ע��")) {
			// Show.toast(AcRegister.this,
			// R.string.user_name_already_exists);
			// } else {
			// Show.toast(AcRegister.this, R.string.connectserverfail);
			// }
			// // Show.toast(AcRegister.this, erro);
			// }

			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			if (pd == null) {
				pd = new ProgressDialog(AcRegister.this);
				// pd.setMessage(getResources()
				// .getString(R.string.user_registting));
			}
			pd.show();
			super.onPreExecute();
		}

		@Override
		protected Integer doInBackground(Void... params) {
			return null;

		}

	}

	public boolean checkPhone(String phone) {
		if ("".equals(phone)) {
			Show.toast(this, R.string.input_not_empty);
			return false;
		} else if (11 != phone.length()) {
			Show.toast(this, R.string.input_right_phone);
			return false;
		} else if (!phone.startsWith("1")) {
			Show.toast(this, R.string.input_right_phone);
			return false;
		}
		return true;

	}

	public boolean checkUser(String name, String pass, String passAgain) {

		if (!("".equals(name) || "".equals(pass))) {
			if (!pass.equals(passAgain)) {
				Show.toast(this, R.string.pass_not_match);
				return false;
			}

			if (pass.length() < 6) {
				password.setError(getResources().getString(
						R.string.error_invalid_password));
				password.requestFocus();
				return false;
			} else {
				return true;
			}
		} else {
			Show.toast(this, R.string.input_not_empty);
			return false;
		}

	}

}
